package com.example.flash_page;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    /**
     * 获取所需权限的字符串里面都是权限名
     */
    private final String[] authority = new String[]{//权限代码
            "android.permission.INTERNET",                //网络权限
            "android.permission.ACCESS_WIFI_STATE",       //获取WiFi网络状态权限
            "android.permission.ACCES_NETWORK_SSTATE",    //获取网络状态权限
            "android.permission.BATTERY_STATE",           //获取电池状态权限
            "android.permission.CHANGE_WIFI_STATE",       //改变WIFI网络连接状态权限
            "android.permission.DELETE_CACHE_FILES",      //删除缓存文件权限
            "android.permission.WRITE_EXTERNAL_STORAGE",  //写入权限
            "android.permission.READ_EXTERNAL_STORAGE"    //读取权限
    };
    /**
     * 文件名
     */
    private final String mFileName = "mydata.txt";//文件名称

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        /**
         * 获取权限代码
         */
        ActivityCompat.requestPermissions(this, authority, 1);
    }

    /**
     * 保存数据
     */
    private void saveData() {
        //获取设备状态
        String state = Environment.getExternalStorageState();
        //如果设备已经挂载
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            //获取SD卡的路径
            File asPath = Environment.getExternalStorageDirectory();
            //生成文件
            File file = new File(asPath, mFileName);
            //写入数据
            String str = "测试文件存储及读取";
            //输出流
            FileOutputStream fos = null;
            try {
                //储存数据
                fos = new FileOutputStream(file);
                fos.write(str.getBytes());
                Toast.makeText(this, "保存数据成功", Toast.LENGTH_SHORT).show();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    //输出流不等于空
                    if (fos != null) {
                        fos.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取数据
     */
    private void readData() {
        //获取设备状态
        String state = Environment.getExternalStorageState();
        //如果设备已经挂载
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            //获取SD卡的路径
            File asPath = Environment.getExternalStorageDirectory();
            //生成文件
            File file = new File(asPath, mFileName);
            //数据
            String str = "";
            //输出流
            FileInputStream fis = null;
            BufferedReader br = null;
            try {
                //储存数据
                fis = new FileInputStream(file);
                br = new BufferedReader(new InputStreamReader(fis));
                str = br.readLine();
                Toast.makeText(this, "读取数据为:" + str + "==============", Toast.LENGTH_SHORT).show();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    //输出流不等于空
                    if (fis != null) {
                        fis.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 重写权限返回处理回调函数
     *
     * @param requestCode  请求码
     * @param permissions  请求的权限
     * @param grantResults 通过的权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean authority_bool = false;
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                for (int j = 0; j < authority.length; j++) {
                    if (authority[j].equals(permissions[i]) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        authority_bool = true;
                        Toast.makeText(this, "权限=================:" + permissions[i] + "申请通过", Toast.LENGTH_SHORT).show();
                        break;
                    } else {
                        authority_bool = false;

                    }
                }
                if (!authority_bool) {
                    Toast.makeText(this, "权限==================:" + permissions[i] + "申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
        Toast.makeText(this, "===============权限申请===============", Toast.LENGTH_SHORT).show();
    }

    /**
     * 读写权限的测试
     *
     * @param view 按钮点击的对象
     */
    public void onClick(View view) {
        if (view.getId() == R.id.main_btn_id) {
            saveData();
        }
        if (view.getId() == R.id.main_btn_id1) {
            readData();
        }
    }
}